package com.ktjiaoyu.mail;

import com.ktjiaoyu.server.pojo.Employee;
import com.ktjiaoyu.server.utils.MailConstants;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Date;

@Component
public class EmailReceiveHandler {
    @Resource
    JavaMailSender javaMailSender;
    @Resource
    MailProperties mailProperties;
    @Resource
    TemplateEngine templateEngine;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MailConstants.MAIL_QUEUE_NAME,durable = "true"),
            exchange = @Exchange(value = MailConstants.MAIL_EXCHANGE_NAME,type = ExchangeTypes.TOPIC),
            key = MailConstants.ROUTING_KEY_NAME
    ))
    public void receive(Message message) throws MessagingException {
        Employee employee=(Employee)message.getPayload();
        //发邮件
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper=new MimeMessageHelper(mimeMessage);
        //发件人
        helper.setFrom(mailProperties.getUsername());
        //收件人
        helper.setTo(employee.getEmail());
        //主题
        helper.setSubject("入职欢迎邮件");
        //发送时间
        helper.setSentDate(new Date());
        //发送内容

        Context context=new Context();
        context.setVariable("name",employee.getName());
        context.setVariable("posName",employee.getPosId());
        context.setVariable("joblevelName",employee.getDepartmentId());
        context.setVariable("departmentName",employee.getDepartmentId());
        String mail = templateEngine.process("mail", context);

        helper.setText(mail,true);

        javaMailSender.send(mimeMessage);

        System.out.println("邮件发送成功");

    }
}
